/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.yunhoo.cqq.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Administrator
 */
public class FileUploadDownloadToolKit {
    public static void download(String fileName) {    
        String name = StrUtil.getShortPathWin(fileName.trim());
        try {
            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.responseComplete();
            String contentType = "application/x-download";
            HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
            response.setContentType(contentType);
            response.setCharacterEncoding("UTF-8");
            StringBuffer contentDisposition = new StringBuffer();
            contentDisposition.append("attachment;");
            contentDisposition.append("filename=\"");
            contentDisposition.append(new String(name.getBytes("gb2312"),"ISO-8859-1"));
            contentDisposition.append("\"");
            response.setHeader("Content-Disposition", new String(contentDisposition.toString()));
            ServletOutputStream out = response.getOutputStream();
            byte[] bytes = new byte[0xffff];
            InputStream is = new FileInputStream(new File(fileName));
            int b = 0;
            while ((b = is.read(bytes, 0, 0xffff)) > 0) {
                out.write(bytes, 0, b);
            }
            is.close();
            out.flush();
            ctx.responseComplete();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
